<?php
header('Content-Type: text/html; charset=UTF-8');
require 'crawl.php';
require 'database.php';
$db = new DB();

// Select games ID
$Qry = 'SELECT id, crawl_url
		FROM games
		WHERE done = 0 AND source = "ebog.com"
		ORDER BY id DESC
		LIMIT 5';
$res = $db->fetchAll($Qry);

foreach ($res as $key=>$value) {
	crawl($value['id'], $value['crawl_url']);
}

function crawl($id, $url) {
	global $db;
	$sth = array("'", '"', 'unityObject.embedUnity', '(', ')', ';');
	$game_file = $width = $height = $howto = $control = '';

	$html = file_get_html($url);

	if ($html->find('div#game-holder', 0))
		$string = $html->find('div#game-holder', 0)->innertext;
	else
		$string = '';

	if (!$string) {
		return false;
		$html->clear();
		unset($html);
	}

	$str = str_get_html($string);

	// Get game
	$pos = strpos($str, '.unity3d');
	if ($pos !== false) {
		$str = strip_tags($str, 'script');
		$str = trim($str);
		$str = str_replace($sth, '', $str);

		// Array
		$array = explode(',', $str);

		$game_file = trim($array[1]);
		$width = trim($array[2]);
		$height = trim($array[3]);
	}

	$pos = strpos($str, 'iframe');
	if ($pos !== false) {
		foreach ($str->find('iframe') as $element){
			$game_file = trim($element->src);
			$width = trim($element->width);
			$height = trim($element->height);
		}
	}

	// Get control
	$howto = $html->find('div#controlslog', 0)->innertext;

	if ($howto) {
		$_string = str_get_html($howto);

		$control = $_string->find('table[border="0"]', 0)->innertext;
		$control = '<table>' . $control . '</table>';
	}
// 	echo $control . '<br /><br /><br />';

	// Get Description
	$desc = $html->find('div[style="text-align: justify; border: none; background-color: #FBF6F2; width: 211px; height: 63px; resize: none; overflow: auto;"]', 0)->innertext;
// 	echo $desc . '<br /><br /><br />';

// 	echo '<br />' . $url . '<br />';
// 	echo $game_file . ' - ' . $width . ' - ' . $height . '<br />';

	if ($game_file) {
		$condition = 'id = ' . $id;

		$games = array(
				'url'=>$game_file,
				'width'=>$width,
				'height'=>$height,
				'done'=>1,
				'active'=>1
		);
		$data = array(
				'infomation'=>$desc,
				'howtoplay'=>$control
		);

		$db->update('games', $games, $condition);
		$db->update('games_description', $data, $condition);

		echo '<div>Game ID ' . $id . ' ==> Okay.</div>';
	}
}